import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { REQUIRE_ROLES } from '../constants/role-index';
import { RoleRespository } from '../repository/role.reposity';


@Injectable()
export class RoleGuard implements CanActivate {

    constructor(
        private reflector: Reflector,
        // private readonly roleRepository: RoleRespository
    ) { }

    async canActivate(
        context: ExecutionContext,
    ): Promise<boolean> {
        // console.log(1);
        let roles: string[] = this.reflector.get<string[]>(REQUIRE_ROLES, context.getHandler());
        // console.log(roles);
        if (!roles) {
            return true;
        }

        const request = context.switchToHttp().getRequest();
        const user = request.user;
        if (!user.roles) {
            throw new UnauthorizedException();
        }
        // const { userId } = request.headers['user-info'];
        // const userRoles = await this.roleRepository.getUserRoles(userId);
        // request.headers['user-roles'] = userRoles;
        //开始判断权限
        if (roles.includes("*")) {
            return true;
        }
        for (let i = 0; i < user.roles.length; i++) {
            const userRole = user.roles[i];
            for (let j = 0; j < roles.length; j++) {
                const r = roles[j];
                if (userRole.roleName.includes(r)) {
                    return true;
                }
            }
        }
        // console.log(user.username, "is not allowed");
        return false;

    }
}   